<template>
  <div class="return-order-edit">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>新增退货单</h2>
        </div>
      </template>

      <!-- 基础信息区域 -->
      <div class="basic-info">
        <h3>基础信息</h3>
        <el-form :model="returnOrderForm" label-width="120px" :rules="rules" ref="returnOrderFormRef">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="退货单号" prop="returnOrderCode">
                <el-input v-model="returnOrderForm.returnOrderCode" placeholder="自动获取系统编号" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="退货日期" prop="returnOrderDate">
                <el-date-picker 
                  v-model="returnOrderForm.returnOrderDate" 
                  type="date" 
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="进货单号" prop="purchaseOrderCode">
                <el-input 
                  v-model="returnOrderForm.purchaseOrderCode" 
                  placeholder="请选择进货单号" 
                  @click="openPurchaseOrderDialog"
                  readonly>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供应商" prop="supplierName">
                <el-input v-model="returnOrderForm.supplierName" placeholder="供应商" readonly></el-input>
                  <!-- 隐藏的供应商ID -->
                  <input type="hidden" v-model="returnOrderForm.supplierId">
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人" prop="contact">
                <el-input v-model="returnOrderForm.contact" placeholder="联系人" readonly></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="联系方式" prop="contactPhone">
                <el-input v-model="returnOrderForm.contactPhone" placeholder="联系方式" readonly></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="部门" prop="departmentName">
                <el-input v-model="returnOrderForm.departmentName" placeholder="所属部门" readonly></el-input>
                  <!-- 隐藏的部门ID -->
                  <input type="hidden" v-model="returnOrderForm.deptId">
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称" prop="customerName">
                <el-input v-model="returnOrderForm.customerName" placeholder="客户名称" readonly></el-input>
                  <!-- 隐藏的客户ID -->
                  <input type="hidden" v-model="returnOrderForm.customerId">
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="退货原因" prop="returnDesc">
                <el-input 
                  v-model="returnOrderForm.returnDesc" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="请输入退货原因">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input 
                  v-model="returnOrderForm.remarks" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="请输入备注信息">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 退货明细区域 -->
      <div class="detail-info">
        <div class="detail-header">
          <h3>退货明细</h3>
          <el-button type="primary" @click="openPurchaseItemsDialog" :disabled="!returnOrderForm.purchaseOrderCode">添加</el-button>
        </div>

        <el-table :data="returnOrderDetails" border style="width: 100%" v-loading="tableLoading">
          <el-table-column type="index" label="序号" width="60"></el-table-column>
          <el-table-column prop="productCode" label="货品编号" width="120"></el-table-column>
          <el-table-column prop="productName" label="货品名称" width="150"></el-table-column>
          <el-table-column prop="productType" label="货品类型" width="100"></el-table-column>
          <el-table-column prop="specificationModel" label="规格型号" width="120"></el-table-column>
          <el-table-column prop="unit" label="单位" width="80"></el-table-column>
          <el-table-column prop="unitPrice" label="单价" width="100"></el-table-column>
          <el-table-column prop="quantity" label="进货数量" width="100"></el-table-column>
          <el-table-column prop="unoutboundQuantity" label="可退数量" width="100"></el-table-column>
          <el-table-column label="退货数量" width="120">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.returnQuantity" 
                :min="1" 
                :max="scope.row.unoutboundQuantity || 0"
                @change="calculateRowAmount(scope.row)"
                size="small">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="退货金额" width="120">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.returnAmount" 
                :precision="2"
                size="small">
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remarks" placeholder="备注" size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removeDetail(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="summary-info">
          <div class="summary-item">
            <span>退货总数量：</span>
            <span>{{ totalQuantity }}</span>
          </div>
          <div class="summary-item">
            <span>退货总金额：</span>
            <span>{{ totalAmount }}</span>
          </div>
        </div>
      </div>

      <div class="form-actions">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
      </div>
    </el-card>

    <!-- 进货单选择弹窗 -->
    <el-dialog
      v-model="purchaseOrderDialogVisible"
      title="选择进货单"
      width="80%"
      destroy-on-close>
      <div class="dialog-search">
        <el-input
          v-model="purchaseOrderSearch"
          placeholder="请输入进货单号"
          style="width: 200px; margin-right: 10px;"
          clearable>
        </el-input>
        <el-button type="primary" @click="searchPurchaseOrders">查询</el-button>
      </div>
      <el-table
        :data="purchaseOrderList"
        border
        highlight-current-row
        @row-click="handlePurchaseOrderSelect"
        style="width: 100%"
        v-loading="dialogLoading">
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="orderCode" label="进货单号" width="150"></el-table-column>
        <el-table-column prop="orderDate" label="进货日期" width="150"></el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="150"></el-table-column>
        <el-table-column prop="contact" label="联系人" width="120"></el-table-column>
        <el-table-column prop="contactPhone" label="联系方式" width="150"></el-table-column>
        <el-table-column prop="departmentName" label="部门" width="150"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="150"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="purchaseOrderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPurchaseOrder">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 进货明细选择弹窗 -->
    <el-dialog
      v-model="purchaseItemsDialogVisible"
      title="选择进货明细"
      width="80%"
      destroy-on-close>
      <div class="dialog-search">
        <el-input
          v-model="purchaseItemsSearch"
          placeholder="请输入货品名称或编号"
          style="width: 200px; margin-right: 10px;"
          clearable>
        </el-input>
        <el-button type="primary" @click="searchPurchaseItems">查询</el-button>
      </div>
      <el-table
        :data="purchaseItemsList"
        border
        @selection-change="handlePurchaseItemsSelectionChange"
        style="width: 100%"
        v-loading="dialogLoading">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="productCode" label="货品编号" width="120"></el-table-column>
        <el-table-column prop="productName" label="货品名称" width="150"></el-table-column>
        <el-table-column prop="productType" label="货品类型" width="100"></el-table-column>
        <el-table-column prop="specificationModel" label="规格型号" width="120"></el-table-column>
        <el-table-column prop="unit" label="单位" width="80"></el-table-column>
        <el-table-column prop="unitPrice" label="单价" width="100"></el-table-column>
        <el-table-column prop="quantity" label="进货数量" width="100"></el-table-column>
        <el-table-column prop="totalAmount" label="进货总金额" width="120"></el-table-column>
        <el-table-column prop="unoutboundQuantity" label="可退数量" width="100"></el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="purchaseItemsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPurchaseItems">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

// 表单数据
const returnOrderFormRef = ref(null);
const returnOrderForm = reactive({
  returnOrderCode: '', // 退货单号
  status: 1, // 状态（默认为草稿）
  returnOrderDate: new Date().toISOString().split('T')[0], // 退货日期（默认为当天）
  purchaseOrderCode: '', // 进货单号
  supplierId: null, // 供应商ID（用于提交到后端）
  contact: '', // 联系人
  contactPhone: '', // 联系方式
  deptId: 1, // 部门ID（用于提交到后端）
  customerId: null, // 客户ID（用于提交到后端）
  returnDesc: '', // 退货原因
  remarks: '' // 备注
});

// 表单验证规则
const rules = {
  status: [{ required: true, message: '请选择退货类型', trigger: 'change' }],
  returnOrderDate: [{ required: true, message: '请选择退货日期', trigger: 'change' }],
  purchaseOrderCode: [{ required: true, message: '请选择进货单号', trigger: 'blur' }],
  returnDesc: [{ required: true, message: '请输入退货原因', trigger: 'blur' }]
};

// 退货明细数据
const returnOrderDetails = ref([]);
const tableLoading = ref(false);

// 进货单选择弹窗
const purchaseOrderDialogVisible = ref(false);
const purchaseOrderSearch = ref('');
const purchaseOrderList = ref([]);
const selectedPurchaseOrder = ref(null);
const dialogLoading = ref(false);

// 进货明细选择弹窗
const purchaseItemsDialogVisible = ref(false);
const purchaseItemsSearch = ref('');
const purchaseItemsList = ref([]);
const selectedPurchaseItems = ref([]);

// 提交状态
const submitting = ref(false);

// 计算属性：退货总数量和总金额
const totalQuantity = computed(() => {
  return returnOrderDetails.value.reduce((sum, item) => {
    return sum + (item.returnQuantity || 0);
  }, 0);
});

const totalAmount = computed(() => {
  return returnOrderDetails.value.reduce((sum, item) => {
    return sum + (item.returnAmount || 0);
  }, 0).toFixed(2);
});

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1: return '草稿';
    case 2: return '待审批';
    case 3: return '已审批';
    case 4: return '已拒绝';
    default: return '未知状态';
  }
};

// 获取状态对应的类型
const getStatusType = (status) => {
  switch (status) {
    case 1: return ''; // 草稿
    case 2: return 'warning'; // 待审批
    case 3: return 'success'; // 已审批
    case 4: return 'danger'; // 已拒绝
    default: return '';
  }
};

// 打开进货单选择弹窗
const openPurchaseOrderDialog = () => {
  purchaseOrderDialogVisible.value = true;
  searchPurchaseOrders();
};

// 查询进货单列表
const searchPurchaseOrders = () => {
  dialogLoading.value = true;
  
  // 构建查询参数
  const params = {};
  if (purchaseOrderSearch.value) {
    params.orderCode = purchaseOrderSearch.value;
  }
  
  // 调用后端API获取进货单列表
  axios.get('/api/ReturnOrder/purchaseOrders', { params })
    .then(response => {
      if (response.data && response.data.code === 200) {
        purchaseOrderList.value = response.data.data || [];
      } else {
        ElMessage.error(response.data?.message || '获取进货单列表失败');
        purchaseOrderList.value = [];
      }
    })
    .catch(error => {
      console.error('获取进货单列表失败:', error);
      ElMessage.error('获取进货单列表失败，请检查网络连接');
      purchaseOrderList.value = [];
    })
    .finally(() => {
      dialogLoading.value = false;
    });
};

// 选择进货单行
const handlePurchaseOrderSelect = (row) => {
  selectedPurchaseOrder.value = row;
};

// 确认选择进货单
const confirmPurchaseOrder = () => {
  if (!selectedPurchaseOrder.value) {
    ElMessage.warning('请选择一个进货单');
    return;
  }
  
  // 将选中的进货单信息填充到表单中
  returnOrderForm.purchaseOrderCode = selectedPurchaseOrder.value.orderCode;
  
  // 保存ID值用于提交到后端
  // 确保将进货单的supplierId赋值给退货单的supplierId
  returnOrderForm.supplierId = Number(selectedPurchaseOrder.value.supplierId);
  // 确保将进货单的deptId赋值给退货单的deptId
  returnOrderForm.deptId = selectedPurchaseOrder.value.deptId;
  // 确保将进货单的userId赋值给退货单的customerId
  returnOrderForm.customerId = selectedPurchaseOrder.value.userId ? Number(selectedPurchaseOrder.value.userId) : Number(selectedPurchaseOrder.value.customerId);
  
  // 保存名称用于页面显示
  returnOrderForm.supplierName = selectedPurchaseOrder.value.supplierName || '';
  returnOrderForm.departmentName = selectedPurchaseOrder.value.departmentName || '';
  returnOrderForm.customerName = selectedPurchaseOrder.value.customerName || selectedPurchaseOrder.value.userName || '';
  
  // 其他信息
  returnOrderForm.contact = selectedPurchaseOrder.value.contact || '';
  returnOrderForm.contactPhone = selectedPurchaseOrder.value.contactPhone || '';
  
  console.log('选择的进货单信息:', {
    // ID值（用于提交到后端）
    supplierId: returnOrderForm.supplierId,
    deptId: returnOrderForm.deptId,
    customerId: returnOrderForm.customerId,
    // 名称（用于页面显示）
    supplierName: returnOrderForm.supplierName,
    departmentName: returnOrderForm.departmentName,
    customerName: returnOrderForm.customerName
  });
  
  // 清空已选择的退货明细
  returnOrderDetails.value = [];
  
  purchaseOrderDialogVisible.value = false;
};

// 打开进货明细选择弹窗
const openPurchaseItemsDialog = () => {
  if (!returnOrderForm.purchaseOrderCode) {
    ElMessage.warning('请先选择进货单号');
    return;
  }
  
  purchaseItemsDialogVisible.value = true;
  searchPurchaseItems();
};

// 查询进货明细列表
const searchPurchaseItems = () => {
  dialogLoading.value = true;
  
  // 构建查询参数
  const params = {
    orderCode: returnOrderForm.purchaseOrderCode
  };
  
  if (purchaseItemsSearch.value) {
    params.keyword = purchaseItemsSearch.value;
  }
  
  // 调用后端API获取进货明细列表
  axios.get(`/api/ReturnOrder/purchaseOrder/code/${returnOrderForm.purchaseOrderCode}/items`, { params })
    .then(response => {
      if (response.data && response.data.code === 200) {
        purchaseItemsList.value = response.data.data || [];
        
        // 过滤掉已经添加到退货明细中的项
        const existingIds = returnOrderDetails.value.map(item => item.purchaseOrderItemId);
        purchaseItemsList.value = purchaseItemsList.value.filter(item => !existingIds.includes(item.id));
      } else {
        ElMessage.error(response.data?.message || '获取进货明细列表失败');
        purchaseItemsList.value = [];
      }
    })
    .catch(error => {
      console.error('获取进货明细列表失败:', error);
      ElMessage.error('获取进货明细列表失败，请检查网络连接');
      purchaseItemsList.value = [];
    })
    .finally(() => {
      dialogLoading.value = false;
    });
};

// 处理进货明细多选
const handlePurchaseItemsSelectionChange = (selection) => {
  selectedPurchaseItems.value = selection;
};

// 确认选择进货明细
const confirmPurchaseItems = () => {
  if (selectedPurchaseItems.value.length === 0) {
    ElMessage.warning('请至少选择一个进货明细项');
    return;
  }
  
  // 将选中的进货明细转换为退货明细
  const newReturnOrderDetails = selectedPurchaseItems.value.map(item => {
    return {
      purchaseOrderItemId: item.id, // 进货明细ID（外键）
      productId: item.productId, // 货品ID
      productCode: item.productCode, // 货品编号
      productName: item.productName, // 货品名称
      productType: item.productType, // 货品类型
      specificationModel: item.specificationModel, // 规格型号
      unit: item.unit, // 单位
      unitPrice: item.unitPrice, // 单价
      quantity: item.quantity, // 进货数量
      unoutboundQuantity: item.unoutboundQuantity, // 可退数量
      returnQuantity: 1, // 默认退货数量为1
      returnAmount: item.unitPrice ? item.unitPrice : 0, // 默认退货金额为单价
      remarks: '' // 备注
    };
  });
  
  // 添加到退货明细列表
  returnOrderDetails.value = [...returnOrderDetails.value, ...newReturnOrderDetails];
  
  purchaseItemsDialogVisible.value = false;
};

// 计算行退货金额
const calculateRowAmount = (row) => {
  if (row.unitPrice && row.returnQuantity) {
    // 计算金额并转换为数字，但存储在returnAmount字段中
    // 提交时会将returnAmount映射到returnMoney
    row.returnAmount = Number((row.unitPrice * row.returnQuantity).toFixed(2));
  }
};

// 移除退货明细
const removeDetail = (index) => {
  returnOrderDetails.value.splice(index, 1);
};

// 提交表单
const submitForm = () => {
  returnOrderFormRef.value.validate((valid) => {
    if (!valid) {
      return;
    }
    
    if (returnOrderDetails.value.length === 0) {
      ElMessage.warning('请至少添加一个退货明细项');
      return;
    }
    
    // 检查退货数量是否合法
    for (const detail of returnOrderDetails.value) {
      if (!detail.returnQuantity || detail.returnQuantity <= 0) {
        ElMessage.warning(`货品 ${detail.productName} 的退货数量必须大于0`);
        return;
      }
      
      if (detail.returnQuantity > detail.unoutboundQuantity) {
        ElMessage.warning(`货品 ${detail.productName} 的退货数量不能大于可退数量`);
        return;
      }
    }
    
    // 检查必要的ID字段
    if (!returnOrderForm.supplierId) {
      ElMessage.warning('供应商ID不能为空');
      return;
    }
    
    if (!returnOrderForm.deptId) {
      ElMessage.warning('部门ID不能为空');
      return;
    }
    
    // 构建提交数据 - 按照图片中的格式
    const submitData = {
      // 退货单主表数据
      returnOrder: {
        returnOrderCode: returnOrderForm.returnOrderCode,
        returnOrderDate: new Date().toISOString(),
        purchaseOrderCode: returnOrderForm.purchaseOrderCode,
        supplierId: Number(returnOrderForm.supplierId),
        contact: returnOrderForm.contact,
        contactPhone: returnOrderForm.contactPhone,
        deptId: returnOrderForm.deptId,
        customerId: Number(returnOrderForm.customerId),
        status: 1,
        returnDesc: returnOrderForm.returnDesc,
        remarks: returnOrderForm.remarks
      },
      
      // 退货明细数据
      returnOrderDetails: returnOrderDetails.value.map(item => ({
        purchaseOrderItemId: Number(item.purchaseOrderItemId),
        returnNumber: Number(item.returnQuantity),
        returnMoney: Number(item.returnAmount),
        remarks: item.remarks || ''
      }))
    };
    
    submitting.value = true;
    
    // 调用后端API提交数据
    // 打印提交数据便于调试
    const jsonData = JSON.stringify(submitData);
    console.log('提交的数据:', jsonData);
    
    // 使用正确的API路径和数据格式
    axios.post('/api/ReturnOrder/withDetails', submitData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(response => {
        if (response.data && response.data.code === 200) {
          ElMessage.success('退货单创建成功');
          router.push('/ReturnOrderView');
        } else {
          ElMessage.error(response.data?.message || '退货单创建失败');
        }
      })
      .catch(error => {
        console.error('退货单创建失败:', error);
        ElMessage.error('退货单创建失败，请检查网络连接');
      })
      .finally(() => {
        submitting.value = false;
      });
  });
};

// 取消操作
const cancel = () => {
  ElMessageBox.confirm('确定要取消编辑吗？未保存的数据将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/ReturnOrderView');
  }).catch(() => {});
};

// 初始化
onMounted(() => {
  // 直接在前端生成退货单号，不再调用可能不存在的后端API
  generateDefaultCode();
});

// 生成默认的退货单号
const generateDefaultCode = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  
  // 生成退货单号：TH + 年月日 + 时分秒 + 3位随机数
  returnOrderForm.returnOrderCode = `TH${year}${month}${day}${hours}${minutes}${seconds}${random}`;
};
</script>

<style scoped>
.return-order-edit {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.basic-info {
  margin-bottom: 30px;
}

.detail-info {
  margin-bottom: 30px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.summary-info {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.summary-item {
  margin-left: 20px;
  font-weight: bold;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.dialog-search {
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
